package com.ppc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ppc.constant.MessageConstant;
import com.ppc.context.BaseContext;
import com.ppc.dto.UserGetMessageDTO;
import com.ppc.dto.UserSendMessageDTO;
import com.ppc.entity.Conversation;
import com.ppc.entity.Employer;
import com.ppc.entity.Message;
import com.ppc.entity.Worker;
import com.ppc.exception.ChatException;
import com.ppc.mapper.user.ChatMapper;
import com.ppc.result.PageResult;
import com.ppc.service.ChatService;
import com.ppc.vo.ConversationVO;
import com.ppc.vo.MessageVO;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 聊天服务的接口的实现，具体注释见service层
 *
 * @author jianKangS1
 * @date 2023/12/20
 */
@Service
public class ChatServiceImpl implements ChatService {


  @Autowired
  ChatMapper chatMapper;


  /**
   * 用户，分页查询我的对话
   *
   * @param pageNum
   * @param pageSize
   * @return {@link PageResult }
   * @description
   */
  @Override
  public PageResult pageQueryEmployer(Integer pageNum, Integer pageSize) {

    PageHelper.startPage(pageNum, pageSize);

    Long userId = BaseContext.getCurrentId();

    Page<ConversationVO> page = chatMapper.employerPageConversationQuery(userId);
    for (ConversationVO conversationVO : page.getResult()) {
      if (conversationVO.getUnreadNumber() == null) {
        conversationVO.setUnreadNumber(0);
      }
    }

    return new PageResult(page.getTotal(), page.getResult());

  }


  /**
   * 雇主发消息
   *
   * @param userSendMessageDTO
   * @description
   */
  @Override
  public void sendMessageEmployer(UserSendMessageDTO userSendMessageDTO) {
    //检查conversation是否存在
    Conversation conversation = Conversation.builder()
        .conversationId(userSendMessageDTO.getConversationId())
        .userIdOne(BaseContext.getCurrentId())
        .build();

    Conversation newConversation = chatMapper.checkConversationExists(conversation);
    if (newConversation == null) {
      throw new ChatException(MessageConstant.CONVERSATION_NOT_EXISTS);
    }
    Message message = Message.builder()
        .conversationId(userSendMessageDTO.getConversationId())
        .messageContent(userSendMessageDTO.getMessageContent())
        .messageTime(LocalDateTime.now())
        .build();
    Long userId = BaseContext.getCurrentId();
    chatMapper.insertMessageForEmployer(userId, message);
  }

  /**
   * 获取某个对话的消息
   *
   * @param userGetMessageDTO
   * @return {@link List }<{@link MessageVO }>
   * @description
   */
  @Override
  public List<MessageVO> getMessage(UserGetMessageDTO userGetMessageDTO) {
    Conversation conversation = Conversation.builder()
        .conversationId(userGetMessageDTO.getConversationId())
        .build();
    Conversation newConversation = chatMapper.checkConversationExists(conversation);
    if (newConversation == null) {
      throw new ChatException(MessageConstant.CONVERSATION_NOT_EXISTS);
    }
    Long currentId = BaseContext.getCurrentId();
    if (newConversation.getUserIdOne() != currentId
        && newConversation.getUserIdTwo() != currentId) {
      throw new ChatException(MessageConstant.CONVERSATION_NOT_BELONG);
    }

    List<MessageVO> messageVOList = chatMapper.selectMessage(userGetMessageDTO.getConversationId(),
        userGetMessageDTO.getTimeAfter());
    return messageVOList;
  }

  /**
   * 工人，发消息
   *
   * @param userSendMessageDTO
   * @description
   */
  @Override
  public void sendMessageWorker(UserSendMessageDTO userSendMessageDTO) {
    //检查conversation是否存在
    Conversation conversation = Conversation.builder()
        .conversationId(userSendMessageDTO.getConversationId())
        .userIdTwo(BaseContext.getCurrentId())
        .build();

    Conversation newConversation = chatMapper.checkConversationExists(conversation);
    if (newConversation == null) {
      throw new ChatException(MessageConstant.CONVERSATION_NOT_EXISTS);
    }

    Message message = Message.builder()
        .conversationId(userSendMessageDTO.getConversationId())
        .messageContent(userSendMessageDTO.getMessageContent())
        .messageTime(LocalDateTime.now())
        .build();
    Long currentUserId = BaseContext.getCurrentId();
    chatMapper.insertMessageForWorker(currentUserId, message);

  }

  /**
   * 雇主，添加和工人的对话
   *
   * @param workerId
   * @return {@link Long }
   * @description
   */
  @Override
  public Long addChatEmployer(Long workerId) {
    //雇主请求，与工人对话
    Long currentId = BaseContext.getCurrentId();
    Worker worker = chatMapper.selectWorkerId(workerId);
    //工人不存在
    if (worker == null) {
      throw new ChatException(MessageConstant.WORKER_NOT_EXISTS);
    }
    Conversation conversation = chatMapper.selectConversation(currentId, worker.getUserId());
    if (conversation != null) {
      return conversation.getConversationId();
    } else {
      conversation = new Conversation();
    }
    conversation.setUserIdOne(currentId);
    conversation.setUserIdTwo(worker.getUserId());
    chatMapper.insertConversation(conversation);
    return conversation.getConversationId();
  }

  /**
   * 工人，添加和雇主的对话
   *
   * @param employerId
   * @return {@link Long }
   * @description
   */
  @Override
  public Long addChatWorker(Long employerId) {
    //工人请求，与雇主对话
    Long currentId = BaseContext.getCurrentId();
    Employer employer = chatMapper.selectEmployerId(employerId);

    Conversation conversation = chatMapper.selectConversation(employer.getUserId(), currentId);
    if (conversation != null) {
      return conversation.getConversationId();
    } else {
      conversation = new Conversation();
    }
    conversation.setUserIdOne(employer.getUserId());
    conversation.setUserIdTwo(currentId);
    chatMapper.insertConversation(conversation);
    return conversation.getConversationId();
  }

  /**
   * 工人，分页查询我的对话
   *
   * @param page
   * @param pageSize
   * @return {@link PageResult }
   * @description
   */
  @Override
  public PageResult pageQueryWorker(Integer page, Integer pageSize) {
    PageHelper.startPage(page, pageSize);
    Long userId = BaseContext.getCurrentId();
    Page<ConversationVO> pageVo = chatMapper.workerPageConversationQuery(userId);
    return new PageResult(pageVo.getTotal(), pageVo.getResult());

  }

  /**
   * 雇主，已读消息
   *
   * @param conversationId
   * @description
   */
  @Override
  public void readMessageEmployer(Long conversationId) {

    Long userId = BaseContext.getCurrentId();
    chatMapper.readMessage(userId, conversationId);
  }

  /**
   * 工人，已读消息
   *
   * @param conversationId
   * @description
   */
  @Override
  public void readMessageWorker(Long conversationId) {
    Long currentworkerId = BaseContext.getCurrentId();
    chatMapper.readMessage(currentworkerId, conversationId);
  }
}
